package com.cssw.fyzb.busi.api.acct;

import com.cssw.fyzb.busi.service.acct.RedPackService;
import com.cssw.fyzb.busi.service.system.SysParamService;
import com.cssw.fyzb.busi.service.user.UserService;
import com.cssw.fyzb.busi.util.NumberUtil;
import com.cssw.fyzb.core.exception.BizException;
import com.cssw.fyzb.core.model.dodb.SysParam;
import com.cssw.fyzb.core.model.dodb.User;
import com.cssw.fyzb.core.util.AesUtil;
import com.cssw.fyzb.core.util.StringUtil;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplelock.SimpleLock;
import com.ydn.simplelock.SimpleLockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

import static com.cssw.fyzb.busi.util.Bizs.ERROR_TRADE_PWD;

/**
 * @Author zhouxu
 * @create 2020-12-23 22:10
 */
@Function(description = "直播间发红包", parameters = {
        @Parameter(name = "userId", type = Type.String, description = "用户标识", required = true),
        @Parameter(name = "liveId", type = Type.String, description = "直播间标识", required = true),
        @Parameter(name = "num", type = Type.Integer, description = "红包个数", required = true),
        @Parameter(name = "money", type = Type.Decimal, description = "红包金额（单位：果子）", required = true),
        @Parameter(name = "title", type = Type.String, description = "标题", required = false),
        @Parameter(name = "tradePwd", type = Type.String, description = "交易密码", required = false),
        @Parameter(name = "effTime", type = Type.String, description = "生效时间", required = false),

})
@Component
public class RedPackLiveSend implements Action {

    private static final Logger logger = LoggerFactory.getLogger(RedPackLiveSend.class);

    @Autowired
    private RedPackService redPackService;

    @Autowired
    SimpleLockFactory simpleLockFactory;

    @Autowired
    SysParamService sysParamService;

    @Autowired
    private UserService userService;

    @Override
    public Response execute(Request request) throws Exception {
        if (true){
            return Response.fail("发红包功能暂未开放");
        }

        String tradePwd = request.getString("tradePwd");
        Long userId = request.getLong("userId");
        User user = userService.getById(userId);
        if (StringUtil.isEmpty(user.getTradePwd())) {
            return Response.fail("您还未设置交易密码");
        }
        if (StringUtil.isEmpty(tradePwd)) {
            return Response.fail("请输入密码");
        }
        if (!AesUtil.encode(tradePwd).equals(user.getTradePwd())) {
            return Response.fail("交易密码错误");
        }
        Integer num = request.getInteger("num");
        Double money = request.getDouble("money");
        String title = request.getString("title");
        Long liveId = request.getLong("liveId");
        String effTime = request.getString("effTime");
        if (userService.hairRedPack(userId) == 1) {
            return Response.fail("您发的红包还未全部领取完！");
        }
        // 获取锁
        SimpleLock lock = simpleLockFactory.getLock("USER_" + userId);
        // 发红包
        try {
            lock.acquire();
            SysParam sysParam = sysParamService.findByCode(SysParam.LIVE_RED_PACK_NUM_UP);
            Integer maxRedPackNum = Integer.valueOf(sysParam.getParamValue());
            if (num > maxRedPackNum) {
                return Response.fail("发送失败，红包个数上限" + maxRedPackNum);
            }

            BigDecimal bigMoney = new BigDecimal(money);

            if (!NumberUtil.isWholeNumber(bigMoney)){
                return Response.fail("红包必须是整数");
            }
            BigDecimal redPackAmountDown = sysParamService.getRedPackAmountDown();
            if (null != redPackAmountDown && redPackAmountDown.compareTo(bigMoney) > 0 ){
                return Response.fail("红包不能小于" + redPackAmountDown.intValue());
            }

            Long redPackId = redPackService.createLiveRedPack(userId, liveId, num, bigMoney, title, effTime);
            return Response.success().put("data", redPackId);
        } catch (BizException biz) {
            logger.error(biz.getErrMsg(), biz.getErrCode());
            return Response.fail(biz.getErrMsg(), biz.getErrCode());
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("发送失败");
        } finally {
            lock.release();
        }

    }
}
